//是否第一次调用showfile函数
var isFirstShowFile = true;
var isShowing = false;
/**
 * 显示文件，下载两次，并且打开文件
 * @param {Object} elementId 文件列表容器
 * @param {Object} files 文件数组
 * @param {Object} mulShow wei true是代表单页面多次引用此函数
 */

mui.init({
	//这点
	gestureConfig: {
		tap: false
	}
});

function showFile(elementId, files, mulShow, knowledgeType) {
	mui.each(files, function(i, item) {
		//判断文件存在不
		plus.io.resolveLocalFileSystemURL("_doc/" + item.wjmc + "." + item.wjlx, function(entry) {
			//文件存在
			addToPdfList(elementId, item, "yxz");
		}, function(e) {
			//文件不存在
			addToPdfList(elementId, item, "wxz");
		});

	})
	if(!isFirstShowFile && !mulShow) {
		return;
	}

	if(isFirstShowFile) {
		mui("body").on("click", ".div_file_item", function() {
			if(isShowing) {
				return;
			}
			var _this = this;
			var documentName = this.wjmc + "." + this.fjlx;
			var fjid = this.fjid;
			var path = "_doc/" + documentName;
			var wjdx = this.wjdx;
			console.log(path);
			if(!mui("#" + fjid)[0].classList.contains("mui-hidden")) {
				return;
			}
			if($(this).find(".wjxz").hasClass("icon-iconchakan")) {
				//文件未下载
				var Intent = plus.android.importClass("android.content.Intent");
				var Uri = plus.android.importClass("android.net.Uri");
				var File = plus.android.importClass("java.io.File");
				var mainActivity = plus.android.runtimeMainActivity();
				intent = new Intent("android.intent.action.VIEW");
				intent.addCategory("android.intent.category.DEFAULT");
		    	intent.setDataAndType(Uri.parse("file:///storage/emulated/0/Android/data/com.lvjing.snjk/apps/H59A6CB69/doc/" + documentName),"application/pdf");
				try {
					mainActivity.startActivity(intent);
				} catch(ex) {
					mui.toast(ex)
				}
			} else {
				//文件不存在
				getme("是否下载该文档", "提示", function() {
					isShowing = false;
					mui(".mui-progressbar").each(function() {
						if(this.id == fjid) {
							downloadDoc(fjid, documentName, this, wjdx);
						}
					});
				}, function() {
					isShowing = false;
				})
			}
		})
	}
	isFirstShowFile = false;
}

function addToPdfList(elementId, item, type) {
	var fragment = document.createElement('li');

	var fileIcon = '';
	switch(item.wjlx) {
		//word文档
		case "doc":
		case "docx":
			fileIcon = "icon-file-word";
			break;
			//txt文件
		case "txt":
			fileIcon = "icon-file-txt";
			break;
			//excel表格
		case "xls":
		case "xlsx":
		case "xlsm":
		case "xlt":
		case "xltx":
		case "xltm":
			fileIcon = "icon-file-excel";
			break;
		case "pdf":
			fileIcon = "icon-file-pdf";
			break;
		default:
			fileIcon = "icon-file-txt";
			break;
	}
	var div = document.createElement("div");
	div.className = "div_file_item";
	div.fjid = item.id;
	div.fjmc = item.zsmc;
	div.wjdx = item.wjdx;
	div.fjlx = item.wjlx;
	div.wjmc = item.wjmc;
	if(typeof(knowledgeType) != "undefined") {
		div.wdlx = knowledgeType;
	}
	var htmlStr = '<div class="div_document_container">' +
		'<div class="div_file_type">' +
		'<span class="span_file_icon iconfont ' + fileIcon + '"></span>' +
		'</div>' +
		'<div class="div_name_and_time_and_size">' +
		'<div class="mui-ellipsis-2 div_file_name">' + item.zsmc + '</div>' +
		'<div>';
	if(item.scsj) {
		htmlStr += '<span class="span_file_time">' + item.scsj + '</span>';
	}

	htmlStr += '<span class="span_file_size">' + bytesToSize(item.wjdx) + '</span>';
	htmlStr += '</div>' +
		'</div>';
	switch(type) {
		case "wxz":
			htmlStr += '<div  class="iconfont  icon-iconGroup wjxz"></div>';
			break;
		case "yxz":
			htmlStr += '<div class="iconfont  icon-iconchakan wjxz"></div>';
			break;
	}
	//选择
	htmlStr += '</div>' +
		'<a id="' + item.id + '" class="mui-progressbar mui-progressbar-in p_progressbar mui-hidden">' +
		'<span></span>' +
		'</a>';
	div.innerHTML = htmlStr;
	fragment.appendChild(div);
	console.log(div.innerHTML);
	mui("#" + elementId)[0].appendChild(fragment);

}

/**
 * 下载文档
 * @param {Object} fjid
 * @param {Object} documentName
 * @param {Object} progressbar
 * @param {Object} totalSize
 */
function downloadDoc(fjid, documentName, progressbar, totalSize) {
	if(plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE) {
		mui.toast('当前网络不给力');
		return;
	}

	var url = SERVER_ADDRESS + TASK_YJXZ + "?param=" + fjid + "&sendByAngent=true";
	//	var url = "http://image.baidu.com/search/down?tn=download&word=download&ie=utf8&fr=detail&url=http%3A%2F%2Fimgsa.baidu.com%2Fexp%2Fw%3D500%2Fsign%3De9bb2fff44166d223877159476230945%2F3b87e950352ac65cac78ce47fcf2b21193138a81.jpg&thumburl=http%3A%2F%2Fimg0.imgtn.bdimg.com%2Fit%2Fu%3D1502764966%2C2806231956%26fm%3D26%26gp%3D0.jpg";
	var task = plus.downloader.createDownload(url, {
		filename: "_doc/" + documentName,
	}, function(task, status) {
		if(status == 200) {
			console.log(task.filename + "下载完成");
			var path = "_doc/" + documentName;
			//plus.runtime.openFile(path, {}, function() {})
			var Intent = plus.android.importClass("android.content.Intent");
			var Uri = plus.android.importClass("android.net.Uri");
			var File = plus.android.importClass("java.io.File");
			var mainActivity = plus.android.runtimeMainActivity();
			intent = new Intent("android.intent.action.VIEW");
			intent.addCategory("android.intent.category.DEFAULT");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.setDataAndType(Uri.parse("file:///storage/emulated/0/Android/data/com.lvjing.snjk/apps/H59A6CB69/doc/" + documentName),"application/pdf");
			try {
				mainActivity.startActivity(intent);
			} catch(ex) {
				mui.toast(ex)
			}

		} else {
			console.log(task.filename + "下载失败，错误" + status);
			mui.toast("下载失败");
		}
	});
	task.addEventListener("statechanged", function(task, status) {
		switch(task.state) {
			case 1: //	此状态难以捕获
				console.log(task.filename + ': 准备就绪');
				break;
			case 2:
				console.log(task.filename + ': 已连接到服务器');
				if(progressbar) {
					progressbar.classList.remove("mui-hidden");
					mui(progressbar).progressbar().setProgress(0);
				}
				break;
			case 3:
				console.log(task.filename + ': 12212');
				if(progressbar) {
					mui(progressbar).progressbar().setProgress(task.downloadedSize / totalSize * 100);
				}
				break;
			case 4:
				console.log(task.filename + ': ' + task.downloadedSize + '/' + totalSize);
				console.log(task.filename + ': 下载完成');
				if(progressbar) {
					progressbar.classList.add("mui-hidden");
					mui(progressbar).progressbar().setProgress(0);
				}
				//下载完成将当前文件置于已下载模式
				$(progressbar).parents("li").find(".wjxz").removeClass("icon-iconGroup");
				$(progressbar).parents("li").find(".wjxz").addClass("icon-iconchakan");
				break;
		}
	});
	task.start();
}

/**
 * 比特换算
 * @param {Object} bytes
 */
function bytesToSize(bytes) {
	if(bytes === 0) {
		return '0 B';
	}
	var k = 1024;
	sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
	i = Math.floor(Math.log(bytes) / Math.log(k));
	return(bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
	//toPrecision(3) 后面保留一位小数，如1.0GB                                                                                                                  //return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}

function selectDoc(successBack, errorBack) {
	plus.nativeUI.showWaiting();
	var isFirstRun = true;
	var Intent = plus.android.importClass("android.content.Intent");
	var Uri = plus.android.importClass("android.net.Uri");
	var mainActivity = plus.android.runtimeMainActivity();
	intent = new Intent(Intent.ACTION_GET_CONTENT);
	//		intent.setType("application/*;text/plain");
	//		intent.setType("text/plain");
	intent.setType("*/*");
	intent.addCategory(Intent.CATEGORY_OPENABLE);
	try {
		mainActivity.startActivityForResult(Intent.createChooser(intent, "请选择一个要上传的文件"),
			100);
	} catch(ex) {
		// Potentially direct the user to the Market with a Dialog
		mui.toast(ex)
	}
	mainActivity.onActivityResult = function(requestCode, resultCode, data) {
		if(!isFirstRun) {
			return;
		}
		plus.nativeUI.closeWaiting();
		isFirstRun = false;
		console.log(requestCode + "," + resultCode + "," + data);
		if(!data) {
			return;
		}
		var uri = data.getData();
		var path = getPath(mainActivity, uri);
		console.log(path)
		var reg = /(.pdf|.docx|.doc|.xlsx|.xls|.txt)$/i;
		if(reg.test(path)) {
			path = "file://" + path;
			plus.io.resolveLocalFileSystemURL(path, function(entry) {
				entry.getMetadata(function(metadata) {
					var _obj = {};
					_obj.fileName = entry.name;
					_obj.fullPath = entry.fullPath;
					successBack && successBack(_obj)
				}, function(err) {
					errorBack && errorBack(err)
					console.log(err.message)
				});
			}, function(err) {
				errorBack && errorBack(err)
				console.log(err.message)
			})
		} else {
			mui.toast("暂不支持上传此类格式的文件");
		}
	}

	function getPath(context, uri) {
		var Build = plus.android.importClass("android.os.Build");
		var DocumentsContract = plus.android.importClass("android.provider.DocumentsContract");
		var Environment = plus.android.importClass("android.os.Environment");
		var ContentUris = plus.android.importClass("android.content.ContentUris");
		var Uri = plus.android.importClass("android.net.Uri");
		var MediaStore = plus.android.importClass("android.provider.MediaStore");

		var isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

		// DocumentProvider
		if(isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
			// ExternalStorageProvider
			if(isExternalStorageDocument(uri)) {
				var docId = DocumentsContract.getDocumentId(uri);
				var split = docId.split(":");
				var type = split[0];

				if("primary" == type.toLocaleLowerCase()) {
					return Environment.getExternalStorageDirectory() + "/" + split[1];
				}
			}
			// DownloadsProvider
			else if(isDownloadsDocument(uri)) {

				var id = DocumentsContract.getDocumentId(uri);
				var contentUri = ContentUris.withAppendedId(
					Uri.parse("content://downloads/public_downloads"), parseInt(id));

				return getDataColumn(context, contentUri, null, null);
			}
			// MediaProvider
			else if(isMediaDocument(uri)) {
				var docId = DocumentsContract.getDocumentId(uri);
				var split = docId.split(":");
				var type = split[0];

				var contentUri = null;
				if("image" == type) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if("video" == type) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if("audio" == type) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}

				var selection = "_id=?";
				var selectionArgs = split[1];

				return getDataColumn(context, contentUri, selection, selectionArgs);
			}
		}
		// MediaStore (and general)
		else if("content" == uri.getScheme().toLowerCase()) {
			return getDataColumn(context, uri, null, null);
		}
		// File
		else if("file" == uri.getScheme().toLowerCase()) {
			return uri.getPath();
		}
		return null;
	}

	/**
	 * Get the value of the data column for this Uri. This is useful for
	 * MediaStore Uris, and other file-based ContentProviders.
	 *
	 * @param context       The context.
	 * @param uri           The Uri to query.
	 * @param selection     (Optional) Filter used in the query.
	 * @param selectionArgs (Optional) Selection arguments used in the query.
	 * @return The value of the _data column, which is typically a file path.
	 */
	function getDataColumn(context, uri, selection, selectionArgs) {
		var Cursor = plus.android.importClass("android.database.Cursor");
		var Context = plus.android.importClass("android.content.Context");
		var cursor = null;
		var column = "_data";
		var projection = ["_data"];

		try {
			cursor = plus.android.invoke(context.getContentResolver(), "query", uri, projection, selection, selectionArgs,
				null);
			if(cursor != null && cursor.moveToFirst()) {
				var column_index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(column_index);
			}
		} finally {
			if(cursor != null)
				cursor.close();
		}
		return null;
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 */
	function isExternalStorageDocument(uri) {
		return "com.android.externalstorage.documents" == uri.getAuthority();
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is DownloadsProvider.
	 */
	function isDownloadsDocument(uri) {
		return "com.android.providers.downloads.documents" == uri.getAuthority();
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 */
	function isMediaDocument(uri) {
		return "com.android.providers.media.documents" == uri.getAuthority();
	}
}

function getme(content, title, successCallBack, errorCallBack) {
	var popConfirmDiv = document.createElement("div"); //创建一个div蒙版
	popConfirmDiv.className = "mui-backdrop pop_confirm animated";
	popConfirmDiv.innerHTML = '<div class="mui-popup mui-popup-in">' +
		'<div class="mui-popup-inner">' +
		'<div class="mui-popup-title"></div>' +
		'<div class="mui-popup-content"></div>' +
		'</div>' +
		'<div class="mui-popup-buttons">' +
		'<span class="mui-popup-button btn_cancel">取消</span>' +
		'<span class="mui-popup-button btn_sure">确定</span>' +
		'</div>' +
		'</div>';
	//	mui("body")[0].appendChild(popConfirmDiv); //创建的div蒙版加载到
	jQuery("body").append(popConfirmDiv);
	mui(".pop_confirm .mui-popup-title")[0].innerText = title;
	mui(".pop_confirm .mui-popup-content")[0].innerText = content;
	//弹出框的确定按钮操作
	mui(".pop_confirm").on("tap", ".btn_sure", function() {
		successCallBack();
		jQuery(".pop_confirm").remove();
	});
	mui(".pop_confirm").on("tap", ".btn_cancel", function() {
		errorCallBack ? errorCallBack() : "";
		jQuery(".pop_confirm").remove();
	});
}
